import config from '../../info/weChat';
import 'whatwg-fetch';

let crypto = require( 'crypto' );

let { appId, key } = config;

// 根据签名算法产生签名
const getSign = obj => {

  let temArr = Object.keys( obj );

  // 对临时数组进行排序
  temArr.sort();

  let temStr = temArr
    .map( el => el + '=' + obj[ el ] )
    .join( '&' );

  // 拼接商户api密钥
  temStr += '&key=' + key;

  console.log( temStr, '中间字符串' );


  // 进行md5签
  return crypto.createHash( 'md5' ).update( temStr, 'utf8' ).digest( 'hex' ).toUpperCase();
};

// 产生一个随机字符串
const getRandomString = () => `${Math.floor( Math.random() * 100000000 )}`;

// 生成时间戳
const getTimeStamp = () => Math.floor( Date.now() / 1000 );


// 微信浏览器内置 WeixinJSBridgeReady 已经准备就绪
const weixinJSBridgeReady = (() => {
  return new Promise( ( resolve, reject ) => {
    if ( typeof WeixinJSBridge === "undefined" ) {
      if ( document.addEventListener ) {
        document.addEventListener( 'WeixinJSBridgeReady', resolve, false );
      } else if ( document.attachEvent ) {
        document.attachEvent( 'WeixinJSBridgeReady', resolve );
        document.attachEvent( 'onWeixinJSBridgeReady', resolve );
      }
    } else {
      resolve();
    }
  } );
})();

// 申请订单
const applyOrder = info => {
  let { total_fee = 1, openid } = info;

  // 从html 中获取code 此code 将用来查找用户的openid
  ;
  if ( !openid ) throw Error( '已授权的html文档竟然没有 openid !!!' );

  let url = '/pay/genIndent?';
  url += 'total_fee=' + encodeURIComponent( total_fee + '' );
  url += '&openid=' + encodeURIComponent( openid );

  // 通知后台生成多少钱的订单
  return fetch( url ).then( res => {
    // 拿到订单信息之后发起支付
    let { status, statusText } = res;
    return new Promise( ( resolve, reject ) => {
      if ( status === 200 ) {
        // 解析json
        res.json().then( json => {
          resolve( JSON.parse( json ) );
        } );
      } else {
        reject( '申请订单数据发生错误: ' + statusText );
      }
    } );
  } );

};

// 发起支付
const payForOrder = orderInfo => {
  // 在微信内置的 weixinJSBridgeReady 准备好后才能发起订单支付
  return weixinJSBridgeReady.then( () => new Promise( ( resolve, reject ) => {
    console.log( orderInfo, '看看订单信息有没有问题先' );


    let { prepay_id } = orderInfo;
    if ( !prepay_id ) throw Error( '服务器返回的订单消息中不含有 prepay_id' );

    let timeStamp = getTimeStamp() + '';
    let nonceStr = getRandomString();

    let params = {
      "appId": appId,
      "timeStamp": timeStamp,
      "nonceStr": nonceStr,   //随机串
      "package": 'prepay_id=' + prepay_id,
      "signType": "MD5"         //微信签名方式：
    };


    params.paySign = getSign( params );


    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', params,
      function ( res ) {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
        if ( res.err_msg === "get_brand_wcpay_request:ok" ) {
          resolve( { state: 'success' } );
        } else {
          resolve({ state: 'error', errMsg: '支付失败' });
        }
      }
    );

  } ) );
};

// info 为订单信息
export const requestPay = info => {
  // 申请订单
  return applyOrder( info )

  // 发起支付
    .then( payForOrder );
};

// 上传弹幕消息
export const uploadData = ( data = {} ) => {
   return fetch('/pay/processMoment', {
    method: 'POST',
    headers: {
      'Accept': 'application/json, text/plain',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify( data)
  });
};






